package com.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.pojo.User;
import com.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SpringSecurityUserService implements UserDetailsService {


    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //通过用户名查询
        User users = userService.queryByUserNameAndRoleAndMenu(s);
        //不等于空则进行认证
        if(users!=null){
            List<GrantedAuthority> list=new ArrayList<>();
            if(users.getRole()!=null && users.getRole().size()>0){
                users.getRole().forEach(r->{
                    list.add(new SimpleGrantedAuthority(r.getKeyword()));

                    if(r.getPermission()!=null && r.getPermission().size()>0){
                        r.getPermission().forEach(p->{
                            list.add(new SimpleGrantedAuthority(p.getKeyword()));
                        });
                    }
                });
            }
            org.springframework.security.core.userdetails.User user=new org.springframework.security.core.userdetails.User(s,users.getPassword(),list);
            return user;
        }
        return null;
    }

}
